/*
 * Register.java
 *
 * Created on Jan 15, 2011, 1:22:40 PM
 */
package edu.rit.varapp.graphical;

import edu.rit.varapp.datalayer.Connect;
import edu.rit.varapp.datalayer.Encryptor;
import edu.rit.varapp.utilities.ExceptionUtils;
import java.awt.Dimension;
import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 * Register view for a client. Allows an existing client to register their email and password into the database.
 * @author Eric Kisner
 */
public class Register extends AbstractView {

    private Login parent;
    private Connect connector;
    private static final int VIEW_WIDTH = 281;
    private static final int VIEW_HEIGHT = 339;

    /** Creates new form Register */
    public Register( Login parent, Connect connector ) {
        super( new Dimension( VIEW_WIDTH, VIEW_HEIGHT ) );
        this.parent = parent;
        this.connector = connector;
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings( "unchecked" )
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        registerButton = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        contactLabel = new javax.swing.JLabel();
        contactField = new javax.swing.JTextField();
        companyLabel = new javax.swing.JLabel();
        companyField = new javax.swing.JTextField();
        emailLabel = new javax.swing.JLabel();
        emailField = new javax.swing.JTextField();
        passwordLabel = new javax.swing.JLabel();
        passwordField = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Register Email");
        setMinimumSize(new java.awt.Dimension(281, 339));
        setPreferredSize(new java.awt.Dimension(281, 339));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });
        getContentPane().setLayout(null);

        jLabel1.setText("REGISTRATION");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(84, 20, 92, 16);

        registerButton.setText("Register");
        registerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                registerButtonActionPerformed(evt);
            }
        });
        getContentPane().add(registerButton);
        registerButton.setBounds(80, 270, 95, 29);

        jPanel1.setLayout(new java.awt.GridLayout(4, 2, -10, 22));

        contactLabel.setText("Contact Name:");
        jPanel1.add(contactLabel);
        jPanel1.add(contactField);

        companyLabel.setText("Company Name:");
        jPanel1.add(companyLabel);
        jPanel1.add(companyField);

        emailLabel.setText("Email:");
        jPanel1.add(emailLabel);
        jPanel1.add(emailField);

        passwordLabel.setText("Password:");
        jPanel1.add(passwordLabel);
        jPanel1.add(passwordField);

        getContentPane().add(jPanel1);
        jPanel1.setBounds(10, 60, 250, 190);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void registerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_registerButtonActionPerformed
        String contactName = contactField.getText();
        String companyName = companyField.getText();
        String email = emailField.getText();
        String password = getPassword();
        if( !validateEmail( email ) ) {
            JOptionPane.showMessageDialog( rootPane, "Please enter a valid email. "
                                                     + "A valid email has the form of: 'example@abc.com'" );
            return;
        }

        boolean success = false;
        try {
            success = connector.register( contactName, companyName, email, password );
        } catch( SQLException sqle ) {
            ExceptionUtils.handleException( sqle, this.getClass() );
        }
        if( !success ) {
            JOptionPane.showMessageDialog( rootPane,
                                           "Registration was unsuccessful. If you have not registered already, "
                                           + "make sure your contact name and company name are correct."
                                           + "\nIf you have already registered, you can log in using your "
                                           + "email and password on the login page." );
            resetFields();
            return;
        } else {
            JOptionPane.showMessageDialog( rootPane, "Registration successful!" );
            this.dispose();
        }
    }//GEN-LAST:event_registerButtonActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        parent.setEnabled( true );
        parent.repaint();
        parent.validate();
        parent.toFront();   //Once we repaint the login view, we want to bring it to the front for convenience.
    }//GEN-LAST:event_formWindowClosed

    /**
     * This method returns the entered text in the password field. For additional security, it is recommended to
     * set each character from the returned password text to 0 once retrieved.
     * @return The hashed password that was entered by the user.
     */
    private String getPassword() {
        char[] pwdText = passwordField.getPassword();
        String password = Encryptor.computeHash( new String( pwdText ) );
        for( int i = 0; i < pwdText.length; i++ ) {
            pwdText[i] = 0;
        }
        return password;
    }

    /**
     * Simple email validation that checks for '@' and '.' characters. We can go more in-depth if we have time.
     * @param email
     * @return
     */
    private boolean validateEmail( String email ) {
        if( email.contains( "@" ) && email.contains( "." ) ) {
            return true;
        }
        return false;
    }

    /**
     * Resets all JTextFields when a user incorrectly enters their contact name, company name, or they have already
     * registered their email or password.
     */
    private void resetFields() {
        companyField.setText( "" );
        contactField.setText( "" );
        emailField.setText( "" );
        passwordField.setText( "" );
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField companyField;
    private javax.swing.JLabel companyLabel;
    private javax.swing.JTextField contactField;
    private javax.swing.JLabel contactLabel;
    private javax.swing.JTextField emailField;
    private javax.swing.JLabel emailLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JButton registerButton;
    // End of variables declaration//GEN-END:variables
}
